package com.glodon.paas.account.security.cas.service;

import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Validate Service Ticket sent from Relaying Parties
 * @deprecated use spring mvc controller instead.
 * @author Don Li
 */
@Deprecated
public class ServiceTicketValidationService extends HttpServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceTicketValidationService.class);

    private CentralAuthenticationService cas;

    @Override
    public void init() throws ServletException {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        cas = (CentralAuthenticationService) context.getBean("centralAuthenticationService");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    private void processRequest(HttpServletRequest req, HttpServletResponse resp) {
        String serviceId = req.getParameter("service");
        String ticket = req.getParameter("ticket");
        LOGGER.debug("do ST validation for ticket : {}, from service : {}", ticket, serviceId);
        Service service = new SimpleWebApplicationServiceImpl(serviceId);
        try {
            Assertion assertion = cas.validateServiceTicket(ticket, service);
        } catch (TicketException e) {
            LOGGER.error("ST validation failed", e);
        }
    }
}
